 /**
 * Description: 物资归还记录
 * @author:Hunter
 * @since:1.0.0
 *
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2018-04-08   Hunter       1.0.0     Initial
 */
package com.metro.paperless.app.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.metro.core.annotation.BusinessDesc;
import com.metro.core.page.Page;
import com.metro.core.vo.JsonResult;
import com.metro.core.vo.QueryParams;
import com.metro.core.vo.ResultCode;
import com.metro.core.vo.inf.IResult;
import com.metro.paperless.app.beans.vo.AppMaterialsReturn;
import com.metro.paperless.app.beans.vo.AppReturnDetail;
import com.metro.paperless.app.beans.vo.AppReturnDetailForm;
import com.metro.paperless.app.service.inf.IAppMaterialsReturnService;
import com.metro.paperless.app.service.inf.IAppReturnDetailService;
import com.metro.paperless.common.beans.constant.DicTypeEnum;
import com.metro.paperless.common.beans.constant.PropertiesEnum;
import com.metro.paperless.common.utils.CreateBarCodeUtils;
import com.metro.paperless.common.utils.DicUtil;
import com.metro.paperless.web.controller.BaseController;
import com.weslink.qsign.util.FtlUtil;
 /**
 * 物资归还记录<br>
 *
 * @author:Hunter
 * @since:1.0.0
 * @version [1.0.0, 2018-04-08]
 */
@Controller
@RequestMapping("/appMaterialsReturn")
public class AppMaterialsReturnController extends BaseController {
    //菜单编码
    private static final String menuCode = "APP_MATERIALS_RETURN";
    //模块描述
    private static final String MODULE_DESC = "物资归还记录";
    @Autowired
    private IAppMaterialsReturnService appmaterialsreturnService;
    @Autowired
    private IAppReturnDetailService appmaterialReturnDetailService;
    @Override
    protected String getViewDir() {
        return "app/lendreturn/";
    }
    
    /**
     * 去查询物资归还记录
     * 
     * @param appmaterialsreturn 物资归还记录页面表单对象
     * @param page 分页配置
     * @return 结果视图
     * @author Hunter
     * @since [1.0.0]
     * @version [1.0.0, 2018-04-08]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "查询物资归还记录列表")
    @RequiresPermissions(menuCode + ":view")
    @SuppressWarnings("all")
    @RequestMapping(value = "list", method = {RequestMethod.GET,RequestMethod.POST})
    public ModelAndView list(AppMaterialsReturn appmaterialsreturn) {
        ModelAndView mav = new ModelAndView();
        try {
            mav.setViewName(getView("appmaterialsreturn_list"));
            mav.addObject("searchEntity", appmaterialsreturn);
        } catch (Exception ex) {
            log.error("查询物资归还记录出错", ex);
            mav.addObject("ex", ex);
            mav.setViewName("/commons/error/error");
        }
        return mav;
    }

    /**
     * 查询物资归还记录
     *
     * @param appmaterialsreturn 物资归还记录页面表单对象
     * @param page 分页配置
     * @return 结果视图
     * @author Hunter
     * @since [1.0.0]
     * @version [1.0.0, 2018-04-08]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "查询物资归还记录列表")
    @RequiresPermissions(menuCode + ":view")
    @SuppressWarnings("all")
    @RequestMapping(value = "dolist", method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public JsonResult dolist(AppMaterialsReturn appmaterialsreturn, Page page, QueryParams<AppMaterialsReturn> queryParams) {
        JsonResult jr = new JsonResult();
        try {
            queryParams.setPaging(page);
            queryParams.setEntity(appmaterialsreturn);
            PageInfo<AppMaterialsReturn> pageInfo = appmaterialsreturnService.queryForPage(queryParams);
            jr.setData(pageInfo);
            jr.setResult(ResultCode.SUCCESS);
        } catch (Exception ex){
            log.error("查询物资归还记录出错",ex);
            jr.setResult(ResultCode.ERROR);
        }
        return jr;
    }

    /**
     * 去新增物资归还记录
     * 
     * @return 结果视图
     * @author Hunter
     * @since [1.0.0]
     * @version [1.0.0, 2018-04-08]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "去新增物资归还记录")
    @RequiresPermissions(menuCode + ":add")
    @RequestMapping(value = "create")
    public ModelAndView createForm(Model model, HttpServletRequest request){
        ModelAndView mav = new ModelAndView();
        try {
            initCreateOrUpdateFrom(mav, "create");
        } catch (Exception ex) {
            log.error("去新增物资归还记录出错", ex);
            mav.addObject("ex", ex);
            mav.setViewName("/commons/error/error");
        }
        return mav;
    }
    
    /**
     * 初始化新增修改物资归还记录所需参数
     * @author Hunter
     */
    private void initCreateOrUpdateFrom(ModelAndView mav, String action){
        mav.addObject("returnStatuss", DicUtil.getLabelValueList(DicTypeEnum.RETURN_STATUS));
        mav.addObject("action", action);
        mav.setViewName(getView("appmaterialsreturn_form"));
    }
    
    /**
     * 新增物资归还记录
     * 
     * @param entity 物资归还记录页面表单对象
     * @param request 请求对象
     * @return 结果视图
     * @author Hunter
     * @since [1.0.0]
     * @version [1.0.0, 2018-04-08]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "新增物资归还记录")
    @RequiresPermissions(menuCode + ":add")
    @RequestMapping(value = "save", method = { RequestMethod.POST})
    @ResponseBody
    public JsonResult saveAppMaterialsReturn(AppMaterialsReturn entity, HttpServletRequest request) {
        JsonResult jr = new JsonResult();
        try {
            IResult res = appmaterialsreturnService.save(entity);
            jr.setResult(res);
            log.debug("新增物资归还记录成功【{}】", entity);
        } catch (Exception ex) {
            log.error("新增物资归还记录出错", ex);
            jr.setResult(ResultCode.ERROR);
        }
        return jr;
    }
    
    
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "新增物资归还记录")
    @RequestMapping(value = "saveAll", method = { RequestMethod.POST})
    @ResponseBody
    public JsonResult saveAppMaterialsReturnAndDetail(AppReturnDetailForm form, AppMaterialsReturn entity, HttpServletRequest request) {
        JsonResult jr = new JsonResult();
        try {
            JsonResult res = appmaterialsreturnService.saveOther(form, entity);
            Long returnId = (Long)res.getData();
            
          //--------------------
        	//--------------------
        	//--------------------
        	//--------------------
        	// 模拟签署成功之后修改物资实际库存
//            AppReturnDetail detail = new AppReturnDetail();
//            detail.setReturnId(returnId);
//            List<AppReturnDetail>  list = appmaterialReturnDetailService.queryForList(detail);
//            appmaterialsreturnService.updateInfo(entity, list);
        	//------------------------
            //--------------------
            //--------------------
            //--------------------
            
            jr.setResult(res);
            jr.setData(returnId);
            log.debug("新增物资归还记录成功【{}】", entity);
        } catch (Exception ex) {
            log.error("新增物资归还记录出错", ex);
            jr.setResult(ResultCode.ERROR);
        }
        return jr;
    }
    
    

    /**
     * 删除物资归还记录
     * 
     * @param id 物资归还记录页面表单对象唯一标识
     * @param request 请求对象
     * @return 结果视图
     * @author Hunter
     * @since [1.0.0]
     * @version [1.0.0, 2018-04-08]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "删除物资归还记录")
    @RequiresPermissions(menuCode + ":delete")
    @RequestMapping(value = "delete/{id}", method = { RequestMethod.DELETE })
    @ResponseBody
    public JsonResult delete(@PathVariable String id, HttpServletRequest request){
        JsonResult jr = new JsonResult();
        try {
            log.debug("删除物资归还记录id={}",id);
            IResult codeMsg = appmaterialsreturnService.deleteByIds(id);
            jr.setResult(codeMsg);
        } catch (Exception ex) {
            log.error("删除物资归还记录出错", ex);
            jr.setResult(ResultCode.ERROR);
        }
        return jr;
    }
    
    /**
     * 去修改物资归还记录
     * 
     * @param id 物资归还记录页面表单对象唯一标识
     * @param request 请求对象
     * @return 结果视图
     * @author Hunter
     * @since [1.0.0]
     * @version [1.0.0, 2018-04-08]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "去修改物资归还记录")
    @RequiresPermissions(menuCode + ":edit")
    @RequestMapping(value = "edit/{id}", method = { RequestMethod.GET})
    public ModelAndView updateForm(@PathVariable Long id, HttpServletRequest request){
        ModelAndView mav = new ModelAndView();
        try {
            AppMaterialsReturn entity = appmaterialsreturnService.getById(id);
            mav.addObject("entity", entity);
            initCreateOrUpdateFrom(mav,"edit");
        } catch (Exception ex) {
            log.error("去修改物资归还记录", ex);
            mav.setView(new RedirectView("list"));
        }
        return mav;
    }

    /**
     * 修改物资归还记录
     * 
     * @param entity 物资归还记录页面表单对象
     * @param request 请求对象
     * @return 结果视图
     * @author Hunter
     * @since [1.0.0]
     * @version [1.0.0, 2018-04-08]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "修改物资归还记录")
    @RequiresPermissions(menuCode + ":edit")
    @RequestMapping(value = "update", method = { RequestMethod.POST})
    @ResponseBody
    public JsonResult updateAppMaterialsReturn(AppMaterialsReturn entity, HttpServletRequest request) {
        JsonResult jr = new JsonResult();
        try {
            IResult res = appmaterialsreturnService.update(entity);
            jr.setResult(res);
            log.debug("修改物资归还记录成功【{}】", entity);
        } catch (Exception ex) {
            log.error("修改物资归还记录出错", ex);
            jr.setResult(ResultCode.ERROR);
        }
        return jr;
    }
    
    /**
     * 去查看物资归还记录
     * 
     * @param id 物资归还记录页面表单对象唯一标识
     * @return 结果视图
     * @author Hunter
     * @since [1.0.0]
     * @version [1.0.0, 2018-04-08]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "去查看物资归还记录详情")
    @RequiresPermissions(menuCode + ":view")
    @RequestMapping(value = "info/{id}", method = { RequestMethod.GET })
    public ModelAndView info(@PathVariable Long id) {
        ModelAndView mav= new ModelAndView();
        try {
            mav.addObject("entity", appmaterialsreturnService.getById(id));
            mav.setViewName(getView("appmaterialsreturn_info"));
        } catch (Exception ex) {
            log.error("查看物资归还记录出错", ex);
        }
        return mav;
        
    }
    
    
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "物资出借签署")
    @RequiresPermissions(menuCode + ":add")
    @RequestMapping(value = "returnSign/{returnId}")
    public ModelAndView lendSignForm(Model model, HttpServletRequest request,@PathVariable String returnId){
        ModelAndView mav = new ModelAndView();
        try {
            @SuppressWarnings("unchecked")
			Map<String,String> resuleMap = createContract(returnId);
            mav.addObject("content",resuleMap);

            Map<String, Object> redoMap= new HashMap<String, Object>();
            redoMap.put("cmd","redo");
            redoMap.put("seq_id",returnId);
            String redo = JSONObject.toJSONString(redoMap);
            mav.addObject("redo",redo);

            Map<String, Object> homeMap= new HashMap<String, Object>();
            homeMap.put("cmd","home");
            homeMap.put("seq_id",returnId);
            String home = JSONObject.toJSONString(homeMap);
            mav.addObject("home",home);

            Map<String, Object> getMap= new HashMap<String, Object>(); //获取图片
            getMap.put("cmd","get");
            getMap.put("seq_id",returnId);
            String get = JSONObject.toJSONString(getMap);
            mav.addObject("get",get);

            Map<String, Object> cancelMap= new HashMap<String, Object>(); //取消
            cancelMap.put("cmd","cancel");
            cancelMap.put("seq_id",returnId);
            String cancel = JSONObject.toJSONString(cancelMap);
            model.addAttribute("cancel",cancel);

            //出借物资
            AppReturnDetail params = new AppReturnDetail();
            params.setReturnId(Long.parseLong(returnId));
            List<AppReturnDetail> appReturnDetailList = appmaterialReturnDetailService.queryForList(params);
            
            //查询物资出借记录
            AppMaterialsReturn entity = appmaterialsreturnService.getById(Long.parseLong(returnId));

            String barCodeImg = CreateBarCodeUtils.generateBaseMsg(entity.getLendCode());
            Map<String, Object> data=new HashMap<String, Object>();
            data.put("matReturnList", appReturnDetailList);
            data.put("entity",entity);
            data.put("barCodeImg", "data:image/png;base64,"+barCodeImg);
            String rootDir = PropertiesEnum.getPropertyValue(PropertiesEnum.FILE_UPLOAD_ROOT);
            FtlUtil.tempalteToFile("return.ftl", data, rootDir+"/"+entity.getIdStr()+".pdf");

            mav.addObject("entity",entity);
            mav.addObject("barCodeImg", "data:image/png;base64,"+barCodeImg);
            String port = PropertiesEnum.getPropertyValue(PropertiesEnum.PAD_PATHPORT);
            mav.addObject("port",port);
            mav.addObject("appReturnDetailList",appReturnDetailList);
            mav.setViewName(getView("appmaterialsreturn_sign"));
        } catch (Exception ex) {
            log.error("去出借单展示页，准备签署", ex);
            mav.addObject("ex", ex);
            mav.setViewName("/commons/error/error");
        }
        return mav;
    }
    
    
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "物资出借签署")
    @RequiresPermissions(menuCode + ":add")
    @RequestMapping(value = "returnSignPrint/{returnId}")
    public ModelAndView returnSignPrint(Model model, HttpServletRequest request,@PathVariable String returnId){
        ModelAndView mav = new ModelAndView();
        try {
            //出借物资
            AppReturnDetail params = new AppReturnDetail();
            params.setReturnId(Long.parseLong(returnId));
            List<AppReturnDetail> appReturnDetailList = appmaterialReturnDetailService.queryForList(params);
            
            //查询物资出借记录
            AppMaterialsReturn entity = appmaterialsreturnService.getById(Long.parseLong(returnId));

            String barCodeImg = CreateBarCodeUtils.generateBaseMsg(entity.getLendCode());
            Map<String, Object> data=new HashMap<String, Object>();
            data.put("matReturnList", appReturnDetailList);
            data.put("entity",entity);
            data.put("barCodeImg", "data:image/png;base64,"+barCodeImg);
            String rootDir = PropertiesEnum.getPropertyValue(PropertiesEnum.FILE_UPLOAD_ROOT);
            FtlUtil.tempalteToFile("return.ftl", data, rootDir+"/"+entity.getIdStr()+".pdf");

            mav.addObject("entity",entity);
            mav.addObject("barCodeImg", "data:image/png;base64,"+barCodeImg);
            String port = PropertiesEnum.getPropertyValue(PropertiesEnum.PAD_PATHPORT);
            mav.addObject("port",port);
            mav.addObject("appReturnDetailList",appReturnDetailList);
            mav.setViewName(getView("appmaterialsreturn_sign_print"));
        } catch (Exception ex) {
            log.error("查看归还记录", ex);
            mav.addObject("ex", ex);
            mav.setViewName("/commons/error/error");
        }
        return mav;
    } 
    
    /**
     * 签署成功保存文件
     * @param itemOut
     * @param entity
     * @param imgStr
     * @param request
     * @return
     */
   @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "确认物资出借")
   @RequiresPermissions(menuCode + ":add")
   @RequestMapping(value = "commitOut", method = { RequestMethod.POST})
   @ResponseBody
   public JsonResult commitOut(AppMaterialsReturn entity,String signName, HttpServletRequest request) {
       JsonResult jr = new JsonResult();
       try {
           Map<String,Object> data = new HashMap<>();

           String id = entity.getIdStr();
           //归还记录
           AppReturnDetail param = new AppReturnDetail();
           param.setReturnId(entity.getId());
           List<AppReturnDetail> appReturnDetailList = appmaterialReturnDetailService.queryForList(param);
           // 查询物资出库记录
           entity = appmaterialsreturnService.getById(Long.valueOf(id));
           entity.setReturnTime(new Date());
           entity.setSignName(signName);

           String barCodeImg = CreateBarCodeUtils.generateBaseMsg(entity.getLendCode());

           data.put("signname",signName);
           data.put("matReturnList", appReturnDetailList);
           data.put("entity",entity);
           data.put("barCodeImg", "data:image/png;base64,"+barCodeImg);
           String rootDir = PropertiesEnum.getPropertyValue(PropertiesEnum.FILE_UPLOAD_ROOT);
           FtlUtil.tempalteToFile("return.ftl", data, rootDir+"/"+entity.getIdStr()+"-signed.pdf");
           
           // 签署成功之后修改物资实际库存
           appmaterialsreturnService.updateInfo(entity, appReturnDetailList);
           log.debug("物资出库成功【{}】", entity);
       } catch (Exception ex) {
           log.error("物资出库出错", ex);
           jr.setResult(ResultCode.ERROR);
       }
       return jr;
    }
   
   @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "查看签署的pdf")
   @RequiresPermissions(menuCode + ":view")
   @RequestMapping(value = "showSignPdf/{id}", method = { RequestMethod.GET})
   public ModelAndView showSignPdf(@PathVariable Long id, HttpServletRequest request){
       ModelAndView mav = new ModelAndView();
       try {
           AppMaterialsReturn entity = appmaterialsreturnService.getById(id);
           mav.addObject("entity", entity);
           initCreateOrUpdateFrom(mav,"edit");
       } catch (Exception ex) {
           log.error("去修改物资归还记录", ex);
           mav.setView(new RedirectView("list"));
       }
       return mav;
   }
}
